package DinnerForScientists;

/**
 * @author welsir
 * @version 1.0
 * @description: TODO
 * @date 2022/10/10 9:54
 */

public class Scientists {

    private static int[] chop = new int[] {0,0,0,0,0};
    private static final String lock = "LOCK";

    class test extends Thread{

        private int id ;
        public test(int id){
            this.id = id;
        }

        @Override
        public void run() {
            while (true){
                thinking();
                isUsed();
                eating();
                unlock();
            }
        }
        public void eating(){
            System.out.println("NumId is:"+id+" is eating...");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        public void thinking(){
            System.out.println("NumId is:"+id+" is thinking...");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        public void isUsed(){
            synchronized (lock){
                if(chop[id]==1||chop[(id+1)%5]==1){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                chop[id] = 1;
                chop[(id+1)%5]=1;
            }
        }
        public void unlock(){
            synchronized (lock){
                chop[id]=0;
                chop[(id+1)%5]=0;
                System.out.println("NumId is:"+id+" is finished eating...");
                lock.notify();
            }
        }
    }
}
